package xin.de.weiauth.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import xin.de.weiauth.bean.AccessToken;
import xin.de.weiauth.bean.WxConfig;
import xin.de.weiauth.config.ProjectUrlConfig;
import xin.de.weiauth.config.WechatAccountConfig;
import xin.de.weiauth.util.WeixinMenuUtil;
import xin.de.weiauth.util.WxUtils;


import java.io.IOException;
import java.text.ParseException;
import java.util.UUID;

@Controller
@Slf4j
public class WxMpController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private ProjectUrlConfig projectUrlConfig;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WechatAccountConfig accountConfig;


    /**
     * 签名
     * @return
     * @throws WxErrorException
     * @throws IOException
     * @throws ParseException
     */
    @GetMapping("/autograph")
    @ResponseBody
    public WxConfig userInfo() throws IOException, ParseException {

        //1、获取AccessToken
        AccessToken accessToken = WeixinMenuUtil.getAccessToken();
        String token = accessToken.getToken();
        log.info(token);
        //2、获取Ticket
        String turl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ token +"&type=jsapi";//这个url链接和参数不能变
        String result = restTemplate.getForObject(turl, String.class);
        JSONObject demoJson = JSONObject.fromObject(result);
        String ticket = demoJson.getString("ticket");
        log.info("jsapi_ticket={}",result);
        //3、时间戳和随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
       log.info("accessToken:"+accessToken+"\njsapi_ticket:"+ticket+"\n时间戳："+timestamp+"\n随机字符串："+noncestr);
        //4、获取url
            String url=projectUrlConfig.wechatMpAuthorize+"/saoma.html";
        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket="+ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
        //6、将字符串进行sha1加密
        String signature = WxUtils.SHA1(str);
        System.out.println("参数："+str+"\n签名："+signature);
        WxConfig wxConfig=new WxConfig();
        wxConfig.setAppId(accountConfig.getMpAppId());
        wxConfig.setNonceStr(noncestr);
        wxConfig.setTimestamp(timestamp);
        wxConfig.setSignature(signature);
        return wxConfig;
    }


}
